//
//  PlayBar.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/6/2.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "PlayBar.h"
#import "MyPlayProgressView.h"

@interface PlayBar()<IGAvPlayerManagerDelegate,MyPlayProgressViewDelegate>

@property (nonatomic, strong)IGAvPlayerManager * manager;
@property (nonatomic, strong)MyPlayProgressView * progressBar;
@property (nonatomic, strong)UILabel * currentTimeLabel;
@property (nonatomic, strong)UILabel * totalTimeLabel;
@property (nonatomic, strong)UIButton * playBtn;
@property (nonatomic, strong)UILabel * downloadProgressLabel;
@property (nonatomic, strong)UILabel * currentScenicPointLabel;

@property (nonatomic, strong)UIButton * nextBtn;
@property (nonatomic, strong)UIButton * PreviousBtn;

@property (nonatomic, strong)UIButton * speedBtn;//播放倍速

@property (nonatomic, assign)CGFloat currentSpeed;//当前播放速度1.0x 1.25x 1.5x

@property (nonatomic, strong)UIButton * sequentialBtn;//顺序播放按钮

@end
@implementation PlayBar

+ (instancetype)shareManeger {
    
    CGFloat  height = 90;
    if (ISiPhoneX) {
        height = 124;
    }
    return [[self alloc] initWithFrame:CGRectMake(0, kScreenHeight - height, kScreenWidth, height)];
    
    //    static PlayBar *manager;
    //
    //    static dispatch_once_t onceToken;
    //    dispatch_once(&onceToken, ^{
    //        manager = [[self alloc] initWithFrame:CGRectMake(0, kScreenHeight - 60, kScreenWidth, 60)];
    //
    //    });
    //    return manager;
}

- (void)awakeFromNib {
    
    [super awakeFromNib];
    
    _manager = [IGAvPlayerManager shareManeger];
    _manager.delegate = self;
    self.backgroundColor = [UIColor whiteColor];
    [self createPlayView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayBarchangePlayStateWith:) name:kIGAvPlayerManagerState object:nil];
}

- (void)setProgressTrackValue:(CGFloat)progressTrackValue {
    
    self.progressBar.trackValue = progressTrackValue;
}
- (void)setProgressValue:(CGFloat)progressValue {
    
    self.progressBar.value = progressValue;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        _manager = [IGAvPlayerManager shareManeger];
        _manager.delegate = self;
        self.backgroundColor = [UIColor whiteColor];
        [self createPlayView];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayBarchangePlayStateWith:) name:kIGAvPlayerManagerState object:nil];
        
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(previousBtnClicked) name:@"remotePre" object:nil];
//
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nextBtnClicked) name:@"remoteNext" object:nil];
    }
    return self;
}


- (void)setHideSequentialBtn:(BOOL)hideSequentialBtn {
    
    _hideSequentialBtn = hideSequentialBtn;
    self.sequentialBtn.hidden = hideSequentialBtn;
    self.PreviousBtn.frame = CGRectMake(self.PreviousBtn.frame.origin.x - 20, self.PreviousBtn.frame.origin.y,self.PreviousBtn.frame.size.width, self.PreviousBtn.frame.size.height);
    self.nextBtn.frame = CGRectMake(self.nextBtn.frame.origin.x + 20, self.nextBtn.frame.origin.y,self.nextBtn.frame.size.width, self.nextBtn.frame.size.height);
    
}
- (void)setLineModel:(LineModel *)lineModel {
    
    _lineModel= lineModel;
    self.manager.lineModel = lineModel;
    _manager.playType = PlayLine;
    
}
- (void)setPointsArray:(NSArray<ScenicPoint *> *)pointsArray {
    
    _pointsArray = [NSMutableArray arrayWithArray:pointsArray];
    _manager.dataSource = pointsArray;
    _manager.playType = PlayLine;
}

- (void)playMusicWithIndex:(NSInteger)index withIsPlay:(BOOL)isImmediately
{
    ScenicPoint * scenicPoint = self.pointsArray[index];
    self.playPath = scenicPoint.playpath;
    [self.manager playMusic:index withIsPlay:isImmediately];
    [self.progressBar setValue:0];
    [self setupSpeed];
}

- (void)setDownloadProgress:(CGFloat)downloadProgress {
    _downloadProgress = downloadProgress;
    _downloadProgressLabel.text = [NSString stringWithFormat:@"%.f%%",downloadProgress * 100];
    if (_downloadState == MCDownloadStateDownloading) {
        [self.downloadBtn setProgress:downloadProgress];
    }
}


- (void)setDownloadState:(MCDownloadState)downloadState {
    _downloadState = downloadState;
    
    dispatch_main_async_safe( ^{
        
        switch (downloadState) {
            case MCDownloadStateDownloading:
            {
                [self.downloadBtn setImage:[UIImage imageNamed:@"continue"] forState:UIControlStateNormal];
                self.downloadProgressLabel.text = @"";
                self.downloadProgressLabel.hidden = NO;
            }
                break;
            case MCDownloadStateCompleted:
            {
                [self.downloadBtn setImage:[UIImage imageNamed:@"complete"] forState:UIControlStateNormal];
                self.downloadProgressLabel.text = @"";
                self.downloadProgressLabel.hidden = YES;
                self.downloadBtn.userInteractionEnabled = NO;
                [self.downloadBtn setProgress:0.f];
            }
                break;
            case MCDownloadStateFailed:
            {
                [self.downloadBtn setImage:[UIImage imageNamed:@"retry"] forState:UIControlStateNormal];
                [self.downloadBtn setProgress:0.f];
                self.downloadProgressLabel.hidden = YES;
            }
                break;
            default:{
                [self.downloadBtn setImage:[UIImage imageNamed:@"download"] forState:UIControlStateNormal];
                [self.downloadBtn setProgress:0.f];
                self.downloadProgressLabel.text = @"";
                self.downloadProgressLabel.hidden = YES;
            }
                break;
        }
    });
    
    
}

- (void)downloadBtnClicked:(UIButton *)btn {
    
    btn.userInteractionEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.688 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        btn.userInteractionEnabled = YES;
    });
    switch (_downloadState) {
        case MCDownloadStateDownloading:
        {
            if (_delegate && [_delegate respondsToSelector:@selector(downloadSuspend)]) {
                [_delegate downloadSuspend];
                _downloadState = MCDownloadStateSuspened;
                [_downloadBtn setProgress:0.f];
                [self setDownloadState:MCDownloadStateNone];
            }
        }
            break;
            
        default:
        {
            
            
            if (![AppManager sharedManager].allowWhenDownload && [AppManager sharedManager].networkState == AFNetworkReachabilityStatusReachableViaWWAN) {
                
                [IGAlertView alertWithTitle:@"" message:MYLocalizedString(@"PUBLIC_NOWIFI_DOWNLOAD_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOWIFI_DOWNLOAD_ALERT_ALLOW", nil) commit:^{
                    
                    [AppManager sharedManager].allowWhenDownload = YES;
                    
                    if (_delegate && [_delegate respondsToSelector:@selector(downloadStart)]) {
                        [_delegate downloadStart];
                    }
                    
                } cancel:nil];
                return;
            }
            
            if (_delegate && [_delegate respondsToSelector:@selector(downloadStart)]) {
                [_delegate downloadStart];
            }
            
        }
            break;
    }
}

- (void)createPlayView {
    
    _speedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _speedBtn.frame = CGRectMake(16, 39, 35, 35);
    [self addSubview:_speedBtn];
    [_speedBtn setImage:[UIImage imageNamed:@"speed1.0x"] forState:UIControlStateNormal];
    [_speedBtn addTarget:self action:@selector(changePlaySpeed) forControlEvents:UIControlEventTouchUpInside];
    [self setupSpeed];//初始化倍速
    UIImage * sequentialImage;
    if ([AppManager sharedManager].allPlayWhenListen){
        sequentialImage =[UIImage imageNamed:@"连续播放"];
    }else{
        sequentialImage = [UIImage imageNamed:@"非连续播放"];
    }
    _sequentialBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _sequentialBtn.frame = CGRectMake(60, 39, 35, 35);
    [self addSubview:_sequentialBtn];
    
    [_sequentialBtn setImage:sequentialImage forState:UIControlStateNormal];
    [_sequentialBtn addTarget:self action:@selector(changePlayOrder) forControlEvents:UIControlEventTouchUpInside];
    
    _downloadBtn = [[ProgressBtn alloc] init];
    _downloadBtn.frame = CGRectMake(self.frame.size.width - 51, 39, 35, 35);
    _downloadBtn.space = 2.f;
    _downloadBtn.progressColor = [UIColor whiteColor];
    [_downloadBtn setImage:[UIImage imageNamed:@"download"] forState:UIControlStateNormal];
    [_downloadBtn addTarget:self action:@selector(downloadBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_downloadBtn];
    
    
    _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:_playBtn];
    _playBtn.frame = CGRectMake(kScreenWidth/2 - 20, 36, 40, 40);
    [_playBtn setImage:[UIImage imageNamed:@"lines_play"] forState:UIControlStateNormal];
    [_playBtn setImage:[UIImage imageNamed:@"lines_pause"] forState:UIControlStateSelected];
    [_playBtn addTarget:self action:@selector(playOrPause) forControlEvents:UIControlEventTouchUpInside];
    
    CGFloat space = 35;
    if (ISiPhone4 || ISiPhone5) {
        space = 10;
    }else if(ISiPhone6 || ISiPhoneX){
        space = 25;
    }
    CGFloat preX = CGRectGetMinX(self.playBtn.frame) - 35 - space;
    _PreviousBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_PreviousBtn addTarget:self action:@selector(previousBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    _PreviousBtn.frame = CGRectMake(preX, 39, 35, 35);
    
    [_PreviousBtn setImage:[UIImage imageNamed:@"audioPre"] forState:UIControlStateNormal];
    [self addSubview:_PreviousBtn];
    
    CGFloat nextX = CGRectGetMaxX(self.playBtn.frame) + space;
    
    _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_nextBtn addTarget:self action:@selector(nextBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    _nextBtn.frame = CGRectMake(nextX, 39, 35, 35);
    [_nextBtn setImage:[UIImage imageNamed:@"audioNext"] forState:UIControlStateNormal];
    [self addSubview:_nextBtn];
    
    
    _downloadProgressLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width - 51,74, 35, 12)];
    _downloadProgressLabel.textColor = kThemeColor;
    _downloadProgressLabel.font = Font(10);
    _downloadProgressLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:_downloadProgressLabel];
   
    _currentTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(16,10, 27, 15)];
    _currentTimeLabel.text = @"00:00";
    _currentTimeLabel.font = Font(8);
    _currentTimeLabel.textColor = kContentColor;
    [self addSubview:_currentTimeLabel];
    
    _progressBar = [[MyPlayProgressView alloc] initWithFrame:CGRectMake(48,15, self.frame.size.width - 96, 3)];
    
    _progressBar.delegate = self;
    _progressBar.playProgressBackgoundColor = kThemeColor;
    _progressBar.trackBackgoundColor = [UIColor grayColor];
    if (self.manager.isPlay) {
        
        [self.playBtn setImage:[UIImage imageNamed:@"lines_pause"] forState:UIControlStateNormal];
        self.progressBar.trackValue = 1.0;
        
        self.progressBar.value = self.manager.progress/self.manager.totaltime;
    }
    [self addSubview:_progressBar];
    
    _totalTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width - 43 ,10, 27, 15)];
    _totalTimeLabel.textAlignment = NSTextAlignmentLeft;
    _totalTimeLabel.text = @"";
    [self addSubview:_totalTimeLabel];
    _totalTimeLabel.font = Font(9);
    _totalTimeLabel.textColor = kContentColor;
    
    self.backgroundColor = [UIColor whiteColor];
    
}

- (void)setupSpeed{
    
//    if ([IGAvPlayerManager shareManeger].isPlay) {
//        
//    }else{
//        self.currentSpeed = 1.0;
//    }
    
    self.currentSpeed = [IGAvPlayerManager shareManeger].playSpeed;
    NSString *str = @"speed1.0x";
    if (self.currentSpeed == 1.25) {
        str = @"speed1.25x";
    }else if(self.currentSpeed == 1.5){
        str = @"speed1.5x";
    }
    [_speedBtn setImage:[UIImage imageNamed:str] forState:UIControlStateNormal];
}

-(void)changePlayOrder {
    if ([AppManager sharedManager].allPlayWhenListen) {
        
        [AppManager sharedManager].allPlayWhenListen = NO;
        [self.sequentialBtn setImage:[UIImage imageNamed:@"非连续播放"] forState:UIControlStateNormal];
    }else {
        [AppManager sharedManager].allPlayWhenListen = YES;
        [self.sequentialBtn setImage:[UIImage imageNamed:@"连续播放"] forState:UIControlStateNormal];
    }
    
}

- (void)changePlaySpeed{
    
    if (self.currentSpeed == 1.0) {
        [_speedBtn setImage:[UIImage imageNamed:@"speed1.25x"] forState:UIControlStateNormal];
        self.currentSpeed = 1.25;
        self.manager.playSpeed = 1.25;
        
    }else if(self.currentSpeed == 1.25){
        
        [_speedBtn setImage:[UIImage imageNamed:@"speed1.5x"] forState:UIControlStateNormal];
        self.currentSpeed = 1.5;
        self.manager.playSpeed = 1.5;
    }else if(self.currentSpeed == 1.5){
        [_speedBtn setImage:[UIImage imageNamed:@"speed1.0x"] forState:UIControlStateNormal];
        self.currentSpeed = 1.0;
        self.manager.playSpeed = 1.0;
    }
}

- (void)previousBtnClicked {
    
    
    self.PreviousBtn.userInteractionEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.PreviousBtn.userInteractionEnabled = YES;
    });
    
    [self.manager previous];
    
}

- (void)nextBtnClicked {
    
    
    self.nextBtn.userInteractionEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.nextBtn.userInteractionEnabled = YES;
    });
    
    [self.manager next];
}

- (void)changeScenicPointTo:(NSInteger)index {
    
    ScenicPoint * point = self.pointsArray[index];
    self.playPath = point.playpath;
    if (_delegate && [_delegate respondsToSelector:@selector(changePointTo:)]) {
        
        [_delegate changePointTo:index];
    }
}
#pragma mark - JSDownloadAnimationDelegate

//- (void)animationStart {
//
//    if (_delegate && [_delegate respondsToSelector:@selector(downloadStart)]) {
//        [self.delegate downloadStart];
//    }
//}
//
//- (void)animationSuspend {
//
//    if (_delegate && [_delegate respondsToSelector:@selector(downloadSuspend)]) {
//        [self.delegate downloadSuspend];
//    }
//}

#pragma mark - progressDelegate

-  (void)beiginSliderScrubbing {
    
    
}

- (void)endSliderScrubbing {
    
    [self.manager musicSeekToTime:self.progressBar.value];
    
}

- (void)sliderScrubbing {
    
    self.currentTimeLabel.text = [_manager timeFormatted:_manager.totaltime - self.progressBar.value * _manager.totaltime];
    
    IGLog(@"----%f",self.progressBar.value);
}

- (void)playOrPause {
    
    if ([IGAvPlayerManager shareManeger].isPlay) {
        [self.manager pause];
        
        if (self.type == 1) {
        } else if (self.type == 2) {
        }
        
    }else {
        [self.manager play];
        
        if (self.type == 1) {
        } else if (self.type == 2) {
        }
    }
}

#pragma mark - avPlayerDelegate

- (void)PlayBarchangePlayStateWith:(NSNotification *)notif
{
    NSInteger state = [notif.userInfo[kIGAvPlayerManagerState] integerValue];
    
    NSString  * url = notif.userInfo[kCurrentPlayURL];
    NSNumber * type = notif.userInfo[kPlayType];
    if (type.integerValue != PlayLine) {
        self.progressBar.value = 0.;
        [self.playBtn setImage:[UIImage imageNamed:@"lines_play"] forState:UIControlStateNormal];
        return;
    }
    switch (state) {
        case AVPlayerPlayStatePreparing:
        case AVPlayerPlayStateBeigin:{
            
            [self.playBtn setImage:[UIImage imageNamed:@"lines_pause"] forState:UIControlStateNormal];
            //[_sliderBtn setImage:[UIImage imageNamed:@"lines_pause"] forState:UIControlStateSelected];
            // self.totalTimeLabel.text = self.manager.durantion;
        }
            break;
        case AVPlayerPlayStatePlaying:
        {
            [self.playBtn setImage:[UIImage imageNamed:@"lines_pause"] forState:UIControlStateNormal];
            
        }
            break;
        case AVPlayerPlayStatePause: {
            [self.playBtn setImage:[UIImage imageNamed:@"lines_play"] forState:UIControlStateNormal];
            
        }
            break;
        case AVPlayerPlayStateEnd:
        {
            self.totalTimeLabel.text = @"00:00";
            [self.playBtn setImage:[UIImage imageNamed:@"lines_play"] forState:UIControlStateNormal];
        }
            break;
        case AVPlayerPlayStateNotPlay:
            
        {
            self.totalTimeLabel.text = @"";
            self.currentTimeLabel.text = @"";
            self.progressBar.value = 0.;
            [self.playBtn setImage:[UIImage imageNamed:@"lines_play"] forState:UIControlStateNormal];
        }
            break;
        case AVPlayerPlayStateseekToZeroBeforePlay:
        {
            self.progressBar.value = 0.;
            
        }
            break;
            
        default:
            break;
    }
    
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)updateBufferProgress:(NSTimeInterval)progress {
    
    self.progressBar.trackValue = progress;
     self.totalTimeLabel.text = self.manager.durantion;
}
- (void)updateProgressWith:(CGFloat)value {
    
//    if (![[IGAvPlayerManager shareManeger].currentURL isEqualToString:self.playPath]) {
//        return;
//    }
    [self.progressBar setValue:value];
    
    self.totalTimeLabel.text = self.manager.durantion;
    self.currentTimeLabel.text = self.manager.currentTime;
//    self.totalTimeLabel.text = self.manager.durantion;
//    IGLog(@"^^^^^^^^^^^^%f",value/self.manager.totaltime);
}


- (void)showBigView:(UIButton *)button {
    if (!button.selected) {
        self.frame = CGRectMake(0, kScreenHeight/3, kScreenWidth, kScreenHeight/3*2);
        button.selected = YES;
        
        
    }else {
        
        self.frame = CGRectMake(0, kScreenHeight - 120, kScreenWidth, 120);
        button.selected = NO;
        
    }
}






//- (void)sliderChange:(UISlider *)slider {
//
//    CGFloat value = slider.value *20;
//
//    [_manager musicSeekToTime:value];
//
//    IGLog(@"%f",value);
//
//}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end

